<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<%
	String path = request.getContextPath();
%>

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>ORDER_LIST</title>
		
		<script src="<%=path%>/static/js/jquery-1.6.1.min.js" type="text/javascript"></script>
		<script src="<spring:url value="/static/js/jquery.easyui.min.js" />" type="text/javascript" ></script>
		<link rel="stylesheet" type="text/css" href="<%=path%>/static/css/themes/default/easyui.css">
		<link href="<%=path%>/static/css/themes/icon.css" rel="stylesheet" type="text/css" />
		
        <%
			String strQueue = (String)request.getAttribute("QUEUE");
        	strQueue = strQueue==null?"":strQueue;
			String strTransaction = (String)request.getAttribute("TRANSACTION");
			strTransaction = strTransaction==null?"":strTransaction;
		%>

	<script type="text/javascript">
	
		var orderListUrl = "";
		var finalOrderListUrl = "orderList";
		<%
		if(!"".equals(strQueue)){
		%>
			orderListUrl = finalOrderListUrl;
		<%
		}
		%>
	
		var toolbar = [{
			text:'BatchAutoClose',
			//iconCls:'icon-save',
			handler:function(){batchAutoClose();}
			},
			{
			text:'BatchManual',
			//iconCls:'icon-ok',
			handler:function(){batchManualClose();}
			}
			,
			{
			text:'BatchAssign',
			//iconCls:'icon-ok',
			handler:function(){batchAssign();}
			}];
		
		var sortIgnoreCase = function(a,b){
            if(!a)a='';
            if(!b)b='';
            var alow = a.toLowerCase();
            var blow = b.toLowerCase();
            return alow==blow?0:(alow>blow?1:-1);
        }

		    var ckstr ="";
			jQuery(function($){
				$('#orderListTable').datagrid({
					title:'Order List',
					method:'post',
					iconCls:'icon-edit',
					fit:true,
					fitColumns: true,
					striped: true,
					singleSelect: false,
					url:orderListUrl,
					sortName: 'OBJECT_ID',
					sortOrder: 'desc',
					remoteSort: true,
					idField:'object_ID',
					queryParams:{QUEUE:"<%=strQueue%>",TRANSACTION:"<%=strTransaction%>"},
					rownumbers:true,
					toolbar:toolbar,
					pagination:true,
					pageSize:20,
					checkOnSelect:false,
					columns:[[
						{field:'ck',checkbox:true},
						{field:'object_NAME',title:'Order ID',width:15,sortable:true,sorter:sortIgnoreCase
						},
						{field:'order_URL_DOMAIN',title:'Site URL / Domain',width:20,sortable:true,sorter:sortIgnoreCase
						},
						{field:'order_STATUS_QUEUE',title:'Order Status',width:20,sortable:true,
							formatter:function(value,row,index){  
								var orderStatusEle = row.order_STATE;
				                if(row.order_STATE != 'PROVISIONING COMPLETE' ){
				                	orderStatusEle = '<a class="orderStatusEleCls" title="Click for current activity..." href="javascript:void(0)" onclick="showCurAcitivity('+row.service_ORDER_ID+')">'+row.order_STATUS_QUEUE+'</a>'; 
				                }else{
				                	orderStatusEle = "&nbsp;&nbsp;"+row.order_STATE;
				                }
				                return orderStatusEle;  
				            },sorter:sortIgnoreCase
						},
						{field:'service_ORDER_TYPE',title:'Order Type',width:10,sortable:true
						},

						{field:'service_EFFECTIVE_DATE',title:'Effective Date',width:10,sortable:true
						},
	                    {field:'assignment',title:'Assignee',width:10,sortable:true
						},
						{field:'branding_REF',title:'Comment',width:10
						},
                      {field:'opt',title:'Action',width:20,
							
				            formatter:function(value,row,index){ 
				                var viewBtn = '<a class="viewocls" title="View" href="javascript:void(0)" srcurl="<%=path%>/order/detail?itemid=' +row.object_ID+ '&orderId=' +row.sales_ORDER_ID+ '&queue=<%=strQueue%>&serviceOrderId=' +row.service_ORDER_ID+ '&orderStatus=' +row.order_STATUS_QUEUE+ '" onclick="openViewFrame(this)">View</a>'; 
				                //var deleteBtn = '&nbsp;<a class="deleteocls" title="Purge" href="javascript:void(0)" onclick="purgeOrder('+row.object_ID+','+row.service_ORDER_ID+')">Purge</a>';
				                
				                var autoCloseBtn = '&nbsp;<a class="autocloseocls" title="Close current open activity without saving." href="javascript:void(0)" onclick="autoCloseActivityAjax('+row.service_ORDER_ID+')">AutoClose</a>';
				                var manualCloseBtn = '&nbsp;<a class="manualcloseocls" title="Manual Provision: Update Inventory." href="javascript:void(0)" onclick="manualCloseOrder(\''+row.service_ORDER_ID +'\',\''+row.object_ID +'\',\''+row.subscription_CODE +'\',\''+row.service_URL +'\')">Manual</a>';
                                //title="Manual Provision:Purge order in WebO2S and Update Inventory." //Now, only update inventory, not purge in WebO2S
                                
				                if(row.order_STATE == 'PROVISIONING COMPLETE' ){
				                	//deleteBtn='';
				                	autoCloseBtn='';
				                	manualCloseBtn='';
				                	ckstr += (index+1)+",";
				                }
				                return viewBtn+autoCloseBtn+manualCloseBtn;
				                
				            }  
				        }
					]],
					
					onLoadSuccess:function(data){
			            
		                var panel = $("#orderListTable").datagrid('getPanel');
		                var checkbox = panel.find('div.datagrid-cell-check input[type=checkbox]');
		                if (data.rows.length) {
		                    for (i = 0; i < data.rows.length; i++) {
		                        if (data.rows[i]["order_STATE"] == "PROVISIONING COMPLETE") {
		                            $(checkbox.get(i)).remove();
		                        }
		                    }
		                }
						
						$('.viewocls').linkbutton({ text:'View',plain:true});
						$('.deleteocls').linkbutton({ text:'Purge', plain:true, iconCls:'icon-remove' });
						$('.autocloseocls').linkbutton({ text:'AutoClose', plain:true });
						$('.manualcloseocls').linkbutton({ text:'Manual', plain:true });
						$('.orderStatusEleCls').linkbutton({ plain:true });
						
						$('#orderListTable').datagrid('clearSelections');
						$('#orderListTable').datagrid('clearChecked');
					},
					onBeforeLoad:function(){
			            ckstr = "";
			        }
				});
		    });
			
			$.ajax({    
		        url:'orderAssignmentList',    
		        dataType : 'json',    
		        type : 'POST',    
		        async:false,  
		        success: function (data){    
		        orderAssignmentList = data;  
		        }    
		  });  
		   

        $.ajaxSetup({
					global : false,
					type : "POST",
					complete : function(XMLHttpRequest, textStatus) {
						var data = XMLHttpRequest.responseText;
						var redirect=window.top.location.host+"/pvconsole/login";
						if (data=="timeout") {
							if (window.top != window.self) {
							   window.top.location.href="${redirect}";
							   return;
							   }
						}
					}
				});
        
				
		function searchOrder() {

			var effDateFrom = $('#SERVICE_EFFECTIVE_DATE_FROM').datetimebox(
					'getValue');
			var effDateTo = $('#SERVICE_EFFECTIVE_DATE_TO').datetimebox(
					'getValue');

			var orderReceiveDateFrom = $('#SERVICE_ORDER_DATE_FROM')
					.datetimebox('getValue');
			var orderReceiveDateTo = $('#SERVICE_ORDER_DATE_TO').datetimebox(
					'getValue');

			if (effDateFrom != "" && effDateTo != "" && effDateTo < effDateFrom) {
				$.messager
						.alert(
								'Warning',
								'Effective Date: To Date should NOT be before From Date ',
								'warning');
			} else if (orderReceiveDateFrom != "" && orderReceiveDateTo != ""
					&& orderReceiveDateTo < orderReceiveDateFrom) {
				$.messager
						.alert(
								'Warning',
								'Order Received Date: To Date should NOT be before From Date ',
								'warning');
			} else {
				reloadOrderDataGrid();
			}

		}

		function clearForm() {
			$('#queryForm').form('clear');
	<%
				if(!"".equals(strQueue)){
				%>
					searchOrder();
				<%
				}else{
				%>
					$('#orderListTable').datagrid('loadData', { total: 0, rows: [] });
					reloadOrderDataGrid();
				<%
				}
				%>
				
			}
			
		    function timeFormatter(date){
		        return date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
		    }
		    function timeParser(date){
		        return new Date(Date.parse(date.replace(/-/g,"/")));
		    }
		    
		   
		    	
		    function myformatter(date) {
				var y = date.getFullYear();
				var m = date.getMonth() + 1;
				var d = date.getDate();
				return y + '-' + (m < 10 ? ('0' + m) : m) + '-'
						+ (d < 10 ? ('0' + d) : d);
			}
			function myparser(s) {
				if (!s)
					return new Date();
				var ss = (s.split('-'));
				var y = parseInt(ss[0], 10);
				var m = parseInt(ss[1], 10);
				var d = parseInt(ss[2], 10);
				if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
					return new Date(y, m - 1, d);
				} else {
					return new Date();
				}
			}
			function purgeOrder(itemid,serviceOrderId) {
				$.messager.confirm('Confirm','Are you sure to purge this order?',function(result){
					if (result){
						var postparams = {"itemid":itemid,"serviceOrderId":serviceOrderId};  
						$.post('purgeOrderAjax',postparams,function(data){
							reloadOrderDataGrid();
	                     });
					}
				});
			}
			
			function autoCloseActivityAjax(serviceOrderId) {
				$.messager.confirm('Confirm','Are you sure to Auto-Close this order?',function(result){
					if (result){
						var postparams = {"serviceOrderId":serviceOrderId}; 
						
						if(typeof(data)=="undefined")
	                      {
	                      $.messager.progress({
	                            title:'Please wait',
	                            msg:'Order is being closed now ...',
	                            text:"Loading..."
	                        });
	                        
	                      }
						 
						$.post('autoCloseActivityAjax',postparams,function(data){
							reloadOrderDataGrid();
						    $.messager.progress('close');
							$.messager.alert('Message',serviceOrderId + " AutoClose: " +data.mes,'info');
	                     });
					}
				});
			}
			
			function manualCloseOrder(pServiceOrderId,pObjectId,pSubsCode,pServiceUrl) {
	            $.messager.confirm('Confirm','Are you sure to Manual-Close this order?',function(result){
	                if (result){
	                   var postparams = {"pServiceOrderId":pServiceOrderId,"pObjectId":pObjectId,"pSubsCode":pSubsCode,"pServiceUrl":pServiceUrl}; 
	                   
	                   if(typeof(data)=="undefined")
	                      {
	                      $.messager.progress({
	                            title:'Please wait',
	                            msg:'Order is being closed now ...',
	                            text:"Loading..."
	                        });
	                        
	                      }
	                   
	                   $.post('manualCloseOrder',postparams,function(data){
	                      reloadOrderDataGrid();

	                      $.messager.progress('close');
	                   $.messager.alert('Message'," Manual-Close: " +data.mes,'info');
	                        });
	                }
	            });
	         }

			
			function insertAssignment(objectId,userId,index){
				
				$('#orderListTable').datagrid('endEdit',index);
				var curRow = $('#orderListTable').datagrid('getRows')[index];
				$.messager.confirm('Confirm','Are you sure to assignment this order?',function(result){
					if (result){
						var postparams = {"objectId":objectId,"userId":curRow.assignment};
						$.post('insertAssignment',postparams,function(data){
							reloadOrderDataGrid();
							$.messager.alert('Message',"Order ID:"+curRow.service_ORDER_ID + " assignment "+data.mes,'info');
	                     });
					}
				});
				
			}
			
			
			function reloadOrderDataGrid() {
				var params = $('#orderListTable').datagrid('options').queryParams;
				var fields =$('#queryForm').serializeArray();
				$.each( fields, function(i, field){
					params[field.name] = field.value;
				});
				$('#orderListTable').datagrid('options').url = finalOrderListUrl;
				$('#orderListTable').datagrid('reload');
			}
			
                var height = window.screen.height-250;  
                var width = window.screen.width;  
                var leftW = 300;  
                if(width>1200){  
                   leftW = 400;  
                }else if(width>1000){  
                   leftW = 350;
                }else {  
                   leftW = 100;
                }  
			
			function openViewFrame(o) {
				$('#idDetailView').html("");
                $('#idDetailView').window('open');
                
                
				$('#idDetailView').append("<div id='idDivWait' style='position:absolute;left:0;width:100%;height:"+height+"px;top:20px;background:#E0ECFF;opacity:0.8;filter:alpha(opacity=80);'>"
				+"<div style='position:absolute;  cursor1:wait;left:40%; top:40%;width:auto;height:16px;padding:12px 5px 10px 30px;"
				+"background:#fff url(../static/css/themes/default/images/loading.gif) no-repeat scroll 5px 10px;border:2px solid #ccc;color:#000;'>"
				+"Loading... Please wait..."
				+"</div></div>");
				
				$('#idDetailView').append('<iframe id="idDetailViewiFrame" frameborder="0" style="width:100%;height:100%;"></iframe>');
				
				$('#idDetailViewiFrame').attr("src",$(o).attr("srcurl"));
            }
			
			function showCurAcitivity(serviceOrderId) {
		    	$('#idCurActivity').dialog({
			        title: 'Current Activity',
			        width: 300,
			        height: 150,
			        closed: false,
			        cache: false,
			        href: 'getOrderStatus?serviceOrderId='+serviceOrderId,
			        modal: true
		        });
		        //$('#idCurActivity').dialog('refresh', 'getCurQAcitivity');
				
			}
			
			function batchAutoClose(){
				
				var checkedItems = $('#orderListTable').datagrid('getChecked');
				if(checkedItems.length > 0){
					var names = [];
					$.each(checkedItems, function(index, item){
						names.push(item.service_ORDER_ID);
					});
					var serviceOrderIdList = names.join(",");
					//alert("serviceOrderIdList="+serviceOrderIdList);
					
					$.messager.confirm('Confirm','Are you sure to Auto-Close these order?',function(result){
						if (result){
							var postparams = {"serviceOrderId":serviceOrderIdList};  
						  if(typeof(data)=="undefined")
	                      {
	                      $.messager.progress({
	                            title:'Please wait',
	                            msg:'Order is being closed now ...',
	                            text:"Loading..."
	                        });
	                        
	                      }  
							$.post('autoCloseActivityAjax',postparams,function(data){
								reloadOrderDataGrid();
								$.messager.progress('close');
								$.messager.alert('Message'," AutoClose: " +data.mes,'info');
		                     });
						}
					});
				}else{
					$.messager.alert('Message',"Please at least select one order to operate!",'info');
				}
			}
			
			function batchManualClose(){
				
				var checkedItems = $('#orderListTable').datagrid('getChecked');
				if(checkedItems.length > 0){
					var names = [];
					$.each(checkedItems, function(index, item){
						names.push(item.object_ID);
					});
					var pObjectIdList = names.join(",");
					//alert("pObjectIdList="+pObjectIdList);
					
					$.messager.confirm('Confirm','Are you sure to Manual-Close this order?',function(result){
						if (result){
							var postparams = {"pObjectId":pObjectIdList};
							
							 if(typeof(data)=="undefined")
	                      {
	                      $.messager.progress({
	                            title:'Please wait',
	                            msg:'Order is being closed now ...',
	                            text:"Loading..."
	                        });
	                        
	                      }  
							$.post('manualCloseOrder',postparams,function(data){
								reloadOrderDataGrid();
								 $.messager.progress('close');
								$.messager.alert('Message'," Manual-Close: " +data.mes,'info');
		                     });
						}
					});
				}else{
					$.messager.alert('Message',"Please at least select one order to operate!",'info');
				}
				
			}
			
			function batchAssign(){
				var checkedItems = $('#orderListTable').datagrid('getChecked');
				if(checkedItems.length <1){
					$.messager.alert('Message',"Please at least select one order to operate!",'info');
				}else{
					$('#idAssignView').dialog('open');
				}
				
			}
			
			function assignOrder(){
				
				var checkedItems = $('#orderListTable').datagrid('getChecked');
				
				if(checkedItems.length > 0){
					var names = [];
					$.each(checkedItems, function(index, item){
						names.push(item.object_ID);
					});
					var pObjectIdList = names.join(",");
					
					var postparams = {"objectIdList":pObjectIdList,"userId":$("#idAssignTo").combobox('getValue')};
						$('#idAssignView').dialog('close');
					$.post('insertAssignment',postparams,function(data){
						reloadOrderDataGrid();
						//$.messager.alert('Message'," Assign order: " +data.mes,'info');
                     });
				}else{
					$.messager.alert('Message',"Please at least select one order to operate!",'info');
				}
				
			}
			
			
			
			//solve the easyui window can't push to left and top side 
			var easyuiWindowOnMove = function(left, top) {  
			    if (left < 0) {  
			       $(this).window('move', {  
			            "left" : 1  
			        });  
			    }  
			    if (top < 0) {  
			        $(this).window('move', {  
			            "top" : 1  
			        });  
			    }  
			    var width = 500;  
			    var height = 400;  
			    var parentWidth = 1055;  
			    var parentHeight = 1000;  
			  
			 
			   if (left > parentWidth - width) {  
			        $(this).window('move', {  
			            "left" : parentWidth - width  
			        });  
			    }  
			   if (top > parentHeight - height) {  
			        $(this).window('move', {  
			           "top" : parentHeight - height  
			       });  
			    }  
			  
			}  
			$.fn.window.defaults.onMove = easyuiWindowOnMove;  
			
			
			
	</script>
		
	</head>


	<body class="easyui-layout" style="height: 100%">
	
		<div data-options="region:'north'" style="height: 130px;">
		
			<form id="queryForm" style="margin:5;text-align: center;">
			<div class="easyui-panel" style="padding: 10px 0 10px 10px"
			title="Search Orders">
				<table width="100%" style="font-size: 12px;">
					<tr>
						<td style="width: 25%">
							<div style="width: 100px;float: left;">Web Order ID:</div> 
							<input name="OBJECT_NAME" style="width: 150">
						</td>
						<td style="width: 25%">
							<div style="width: 100px;float: left;">Order Type: </div>
							<select class="easyui-combobox" name="SERVICE_ORDER_TYPE" style="width:160px;" panelHeight="auto">
								<option value="">Select</option>
								<option value="Provide">Provide</option>
								<option value="Amend">Amend</option>
								<option value="Transfer">Transfer</option>
								<option value="Suspend">Suspend</option>
								<option value="Cease">Cease</option>
								<option value="Resume">Resume</option>
								<option value="Terminate">Terminate</option>
							</select>
						</td>

						<td style="width: 30%">
							<div style="width: 100px;float: left;">Service Effective Date:</div>
							<input name="SERVICE_EFFECTIVE_DATE_FROM" id="SERVICE_EFFECTIVE_DATE_FROM" style="width:100px" class="easyui-datebox" data-options="editable:false,formatter:myformatter,parser:myparser"> &nbsp; ~ &nbsp; 
							<input name="SERVICE_EFFECTIVE_DATE_TO" id="SERVICE_EFFECTIVE_DATE_TO" style="width:100px" class="easyui-datebox" data-options="editable:false,formatter:myformatter,parser:myparser">
						</td>
						<td style="width: 20%">
						<div style="width: 80px;float: left;">Assignee:</div>
						 <input name="ASSIGNMENT" class="easyui-combobox" style="width:120px" data-options="valueField:'USER_ID',textField:'ASSIGNMENT',data:orderAssignmentList"></div>         
						  </td>
                        </tr>
					<tr>
						<td style="width: 25%">
							<div style="width: 100px;float: left;">Site URL: </div>
							<input name="SERVICE_URL" style="width: 150">
						</td>
						<td style="width: 25%" >
							<div style="width: 100px;float: left;">Order Status: </div>
							<select class="easyui-combobox" name="SERVICE_ORDER_STATUS" style="width:160px;"  panelHeight="auto">
								<option value="">Select</option>
								<option value="WEBEX OPS VERIFICATION QUEUE">Verify Blis Order</option>
								<option value="WEBEX OPS AUTO FAIL QUEUE">Auto failures</option>
								<option value="WEBEX OPS MANUAL PV QUEUE">Manual service</option>
								<option value="WEBEX OPS BRANDING QUEUE">Pending Branding</option>
								<option value="WAIT FOR SED">Waiting for effective date</option>
								<option value="WAIT FOR DNS">Wait for Site DNS</option>
							</select>
						</td>
						

						<td style="width: 30%">
							<div style="width: 100px;float: left;">CPF Order Receive Date: </div> 
							<input name="SERVICE_ORDER_DATE_FROM" id="SERVICE_ORDER_DATE_FROM" style="width:100px" class="easyui-datebox" data-options="editable:false,formatter:myformatter,parser:myparser"> &nbsp; ~ &nbsp; 
							<input name="SERVICE_ORDER_DATE_TO" id="SERVICE_ORDER_DATE_TO" style="width:100px" class="easyui-datebox" data-options="editable:false,formatter:myformatter,parser:myparser">
						</td>
						  <td style="width: 20%">
		             <a href="#" onclick="searchOrder();" class="easyui-linkbutton" iconCls="icon-search"><div style="width: 20px;float: left;">Query</div></a>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;
		             <a href="#" onclick="clearForm();" class="easyui-linkbutton" iconCls="icon-search"><div style="width: 20px;float: left;">Clear</div></a>		            
						</td>

					</tr>
				</table>
			</div>
		</form>
	</div>
		
		<div data-options="region:'center'" style="padding:10; " id="tabdiv">

			<table id="orderListTable"></table>
		</div>
		
		<div id="idCurActivity"></div>
		<div id="idAssignView1" title="Assign Order View"  class="easyui-window" data-options="closed:true,iconCls:'icon-save'" style="width:300px;height:180px;">
		<div id="idAssignView" class="easyui-dialog" title="Assign Order View" style="width:400px;height:200px;padding:10px;text-align: center;margin:0px auto;vertical-align: middle;"
				data-options="
					iconCls: 'icon-save',
					closed:'true',
					buttons: '#dlg-buttons'
				">
				<br/><br/>
			Assign to: <input id="idAssignTo" class="easyui-combobox" data-options="valueField:'USER_ID',textField:'ASSIGNMENT',data:orderAssignmentList">
		</div>
		<div id="dlg-buttons">
			<a href="javascript:void(0)" class="easyui-linkbutton" onclick="javascript:assignOrder()">Assign</a>
			<a href="javascript:void(0)" class="easyui-linkbutton" onclick="javascript:$('#idAssignView').dialog('close')">Close</a>
		</div>
		<div id="idDetailView" title="Detail View"  class="easyui-window" data-options="closed:true,iconCls:'icon-save'" style="width:755px;height:440px;">
	 	</div> 
	</body>
